<?php
namespace app\wxwork\controller;

use app\wxwork\logic\OAuth;
use think\Request;
use think\Db;
use app\custom_user\model\UserSession;
use app\custom_user\logic\UserOutsideLogic;
use app\custom_user\model\UserModel;
use cmf\controller\HomeBaseController;
use app\custom_user\controller\IndexController;
use app\wxwork\logic\WXWork;

/**
 * 企业微信提供了OAuth的扫码登录授权方式
 * 目前支持authorization_code模式
 */
class OAuthController extends IndexController
{
    //在当前页面上显示登录二维码
    public function authWithEmbedQRCode()
    {
        $dom_id="wx-qr";
        $callback=Request::instance()->domain().url("callback");
        $wxwork=new WXWork();
        $params=[
            "id" => $dom_id,
            "appid" => $wxwork->corpID,
            "agentid" => $wxwork->agentID,
            "redirect_uri" => $callback ,
            "state" => "2333",
            // "href" => "",//引用样式的链接
        ];
        $html="<div id='$dom_id'></div>";
        $html.='<script src="http://rescdn.qqmail.com/node/ww/wwopenmng/js/sso/wwLogin-1.0.0.js"></script>';
        $html.='<script>window.WwLogin('.json_encode($params).');</script>';
        return $html;
    }
    //重定向到企业微信的页面，显示登录二维码
    public function authWithQRCode()
    {
        $wxwork=new WXWork();
        $callback=Request::instance()->domain().url("callback");
        $url="https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid=".$wxwork->corpID
            ."&agentid=".$wxwork->agentID
            ."&redirect_uri=".urlencode($callback)
            ."&state=".urlencode("2333");
        $this->redirect($url);
    }
    //在企业微信内置的浏览器中打开，直接进行授权
    public function authWithClient()
    {
        $scope="snsapi_userinfo";
        $wxwork=new WXWork();
        $callback=Request::instance()->domain().url("callback");
        $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$wxwork->corpID
            ."&agentid=".$wxwork->agentID
            ."&redirect_uri=".urlencode($callback)
            ."&state=".urlencode("2333")
            ."&response_type=code&scope=$scope#wechat_redirect";
        $this->redirect($url);
    }
    //接收企业微信重定向后传来的code
    public function callback()
    {
        $state=input("state");

        //根据code获取成员信息
        if(!isset($_GET["code"])){
            $this->error("验证失败");
        }
        $wxwork=new WXWork();
        $url="https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=".$wxwork->getToken()."&code=".$_GET["code"];
        $info=$wxwork->get($url);
        if(!$info){
            $this->error("验证码已失效",url("custom_user/Index/login"));
        }

        //检查用户是否已经注册
        $uol=new UserOutsideLogic();
        $user=$uol->loginOutsideUser($info["UserId"]);
        if($user){
            $this->loginRedirect();
        }

        //使用user_ticket获取成员详情
        if(isset($info["user_ticket"])){
            $url="https://qyapi.weixin.qq.com/cgi-bin/user/getuserdetail?access_token=".$wxwork->getToken();
            $detail=$wxwork->post($url,[
                "user_ticket"=>$info["user_ticket"]
            ]);
        }
        $this->assign("UserId",$info["UserId"]);
        if(!isset($detail)){
            $detail=Db::table("ww_user")->where(["userid"=>$info["UserId"]])->find();
        }
        session("detail",$detail);
        $this->assign("detail",$detail);
        return $this->fetch("bind");
    }
    public function bindOutsideUser()
    {
        $UserId=input("UserId");
        $username=input("username");
        $password=input("password");

        $um=new UserModel();
        $user=$um->checkUser(["username"=>$username],$password);
        if(!$user){
            $this->error=$um->getError();
            return false;
        }
        $um->loginUser($user);
        UserSession::set($user);

        $uol=new UserOutsideLogic();
        $result=$uol->bindOutsideUser($user["id"],$UserId,"wxwork","userid");
        if(!$result){
            $this->error($wxwork->getError());
        }
        $this->loginRedirect();
    }
    public function bindOutsideUserWithDetail()
    {
        $detail=session("detail");
        if(!$detail){
            $this->error("获取用户信息失败");
        }
        $data=[
            "username"=>$detail["userid"],
            "nickname"=>$detail["name"],
            "mobile"=>$detail["mobile"]
        ];
        $uol=new UserOutsideLogic();
        $result=$uol->createOutsideUser($data,$detail["userid"],"wxwork","userid");
        if(!$result){
            $this->error($wxwork->getError());
        }
        $this->loginRedirect();
    }
}
